import { cloneDeep } from 'lodash';

import { queryAppPermList } from '@/api/applicationManagement';
import { PordDefaultData } from '@/enums/commonEnum';

interface AppTypeCode {
  app: number | string;
  component: number | string;
}

export const useEditTree = (props: AppTypeCode) => {
  const searchValue = ref('');
  // 展开的节点
  const expandedKeys = ref<string[]>([]);
  // 选中的节点
  const selectedKeys = ref<string[]>([]);
  const initTreeData = ref<any[]>([]);
  const treeData = ref<any>([]);
  const selectNode = ref<any>(null);
  const loadingTree = ref<boolean>(false);
  // id=> 只能传字符串:选中节点的_id ; appId=> 可以传以逗号分隔的字符串:展开节点的_id
  const getTreeData = async (id?: string, appId?: string) => {
    loadingTree.value = true;
    await queryAppPermList({ projectCode: PordDefaultData.projectCode })
      .then(async (res) => {
        const resData = await addCode(res);
        treeData.value = resData;
        initTreeData.value = cloneDeep(treeData.value);
        if (treeData.value.length > 0) {
          // id查询数据中是否存在选中ID
          const idFlag = flattenTreeData(treeData.value).some((item: any) => item._id === id);
          let appIdList: any = appId?.split(',') || [];
          // 判断appId转义后是否存在展开ID
          appIdList = appIdList.reduce((acc: any, cur: any) => {
            const flag = flattenTreeData(treeData.value).some((item: any) => item._id == cur);
            if (flag) {
              acc.push(cur);
            }
            return acc;
          }, []);

          // 新增时默认选中新增的节点
          if (id && idFlag) {
            selectedKeys.value = [id];
            selectNode.value = flattenTreeData(treeData.value).find((item: any) => item._id === id);
          }
          // 展开的节点
          if (appId && appIdList) expandedKeys.value = appId.split(',');

          // 默认选中第一个节点
          if (!id && !appId) {
            treeData.value?.length && selectedKeys.value.push(treeData.value[0]._id);
            selectNode.value = (treeData.value?.length && treeData.value[0]) || null;
            selectedKeys.value = [treeData.value[0]._id];
          }
        }
      })
      .finally(() => {
        loadingTree.value = false;
      });
  };

  //递归循环增加唯一值
  const addCode = (data: any) => {
    return new Promise((resolve) => {
      data.forEach((item: any) => {
        item._id = item?.components ? `app_id${item.code}` : `components_id${item.applicationCode}${item.code}`;
        item._type = item?.components ? props.app : props.component;
        if (item.components && item.components.length) {
          addCode(item.components);
        }
      });
      resolve(data);
    });
  };

  // 平铺树数据
  const flattenTreeData = (data: any, level = 0) => {
    const result: any = [];
    data.forEach((item: any) => {
      result.push({
        ...item,
        level,
      });
      if (item.components && item.components.length > 0) {
        result.push(...flattenTreeData(item.components, level + 1));
      }
    });
    return result;
  };

  //编辑树
  const handleEdit = (data: any) => {};

  const onSearch = (e: any) => {
    const val = e.target.value;
    expandedKeys.value = [];
    if (!val) {
      expandedKeys.value = [`app_id${selectNode.value.applicationCode}`];
      treeData.value = initTreeData.value;
      return false;
    }
    const cloneTreeData = cloneDeep(initTreeData.value);
    treeData.value = filterSearchValue(cloneTreeData, val);
    // 搜索到之后打开所有节点
    const arr: string[] = [];
    val && getExpandedKeys(cloneTreeData, arr);
    expandedKeys.value = arr;
  };

  // 获取选中的节点
  const getExpandedKeys = (tree: any, arr: string[]) => {
    tree.forEach((item: any) => {
      arr.push(item._id);
      if (item.components && item.components.length) {
        getExpandedKeys(item.components, arr);
      }
    });
  };

  // 过滤树节模糊匹配后选中数据
  function filterSearchValue(tree: any, val: string) {
    return tree.filter((item: any) => {
      if (item.name.indexOf(val) > -1) {
        return true;
      } else if (item.components && item.components.length) {
        const res = filterSearchValue(item.components, val);
        if (res.length) {
          item.components = res;
          return true;
        }
      }
      return false;
    });
  }

  return {
    searchValue,
    onSearch,
    expandedKeys,
    selectedKeys,
    treeData,
    handleEdit,
    getTreeData,
    selectNode,
    loadingTree,
  };
};
